package com.examlpe.lotterysystem.controller;
import java.util.Date;

import com.examlpe.lotterysystem.common.pojo.CommonResult;
import com.examlpe.lotterysystem.controller.param.DrawPrizeParam;
import com.examlpe.lotterysystem.controller.param.ShowWiningRrecordsParam;
import com.examlpe.lotterysystem.controller.result.WiningRecordsResult;
import com.examlpe.lotterysystem.service.DrawPrizeService;
import com.examlpe.lotterysystem.service.dto.WiningRecordsDTO;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class DrawPrizeController {

    @Autowired
    private DrawPrizeService drawPrizeService;

    @RequestMapping("/draw/prize")
    public CommonResult<Boolean> drawPrize(
            @RequestBody @Valid DrawPrizeParam param) {
        log.info("drawPrize DrawPrizeParam{}",param);
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WiningRecordsResult>> showWiningRecords(
            @Valid @RequestBody ShowWiningRrecordsParam param) {
        log.info("WiningRecordsResult ShowWiningRrecordsParam{}",param);
        List<WiningRecordsDTO> winingRecordsDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(
                ConvertToWiningRecordsResultList(winingRecordsDTOList));
    }

    private List<WiningRecordsResult> ConvertToWiningRecordsResultList(List<WiningRecordsDTO> winingRecordsDTOList) {
        if(CollectionUtils.isEmpty(winingRecordsDTOList)) {
            return Arrays.asList();
        }
        return winingRecordsDTOList.stream().map(
                winingRecordsDTO -> {
                    WiningRecordsResult winingRecordsResult = new WiningRecordsResult();
                    winingRecordsResult.setWinnerId(winingRecordsDTO.getWinnerId());
                    winingRecordsResult.setWinnerName(winingRecordsDTO.getWinnerName());
                    winingRecordsResult.setPrizeName(winingRecordsDTO.getPrizeName());
                    winingRecordsResult.setPrizeTier(winingRecordsDTO.getPrizeTier().getMessage());
                    winingRecordsResult.setWinningTime(winingRecordsDTO.getWinningTime());
                    return winingRecordsResult;
                }
               ).collect(Collectors.toList());
    }
}
